<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 6.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.jpg">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.jpg">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"matian.connorma.cn","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="代码来自于Spring Boot 2.0.4.RELEASE SpringApplication类负责由main方法启动spring应用，文档中给出了启动的主要步骤：  创建ApplicationContext 处理命令行参数 refresh ApplicationContext，加载bean 触发各类Runner">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring Boot 启动流程简记">
<meta property="og:url" content="http://matian.connorma.cn/a5d8fb53.html">
<meta property="og:site_name" content="马天">
<meta property="og:description" content="代码来自于Spring Boot 2.0.4.RELEASE SpringApplication类负责由main方法启动spring应用，文档中给出了启动的主要步骤：  创建ApplicationContext 处理命令行参数 refresh ApplicationContext，加载bean 触发各类Runner">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2019-11-01T09:57:21.000Z">
<meta property="article:modified_time" content="2024-01-25T12:19:17.206Z">
<meta property="article:author" content="马天">
<meta property="article:tag" content="java">
<meta property="article:tag" content="Spring Boot">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://matian.connorma.cn/a5d8fb53.html">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Spring Boot 启动流程简记 | 马天</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">马天</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://matian.connorma.cn/a5d8fb53.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="马天">
      <meta itemprop="description" content="程序猿">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="马天">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Spring Boot 启动流程简记
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-11-01 17:57:21" itemprop="dateCreated datePublished" datetime="2019-11-01T17:57:21+08:00">2019-11-01</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Spring/" itemprop="url" rel="index"><span itemprop="name">Spring</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>代码来自于Spring Boot 2.0.4.RELEASE</p>
<p>SpringApplication类负责由main方法启动spring应用，文档中给出了启动的主要步骤：</p>
<ul>
<li>创建ApplicationContext</li>
<li>处理命令行参数</li>
<li>refresh ApplicationContext，加载bean</li>
<li>触发各类Runner</li>
</ul>
 <span id="more"></span>

<h2 id="SpringApplication的初始化"><a href="#SpringApplication的初始化" class="headerlink" title="SpringApplication的初始化"></a>SpringApplication的初始化</h2><p>main函数中通过SpringApplication类的静态方法run()开始流程，SpringApplication类首先将main函数所在的类作为primarySource来初始化一个SpringApplication的实例，作为primarySource是指“load beans from the specified primary sources”，SpringApplication实例化包括的流程有：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// resourceLoader用于从classPath或者文件系统加载资源文件</span></span><br><span class="line"><span class="comment">// ResourceLoader这个类是一个策略模式的接口，有ApplicationContext、DefaultResourceLoader等多个实现</span></span><br><span class="line"><span class="built_in">this</span>.resourceLoader = resourceLoader;</span><br><span class="line">Assert.notNull(primarySources, <span class="string">&quot;PrimarySources must not be null&quot;</span>);</span><br><span class="line"><span class="comment">// 加载primarySources，因为是一个Set所以可看出有多个sources，SpringApplication类文档也说明了可以进行设置</span></span><br><span class="line"><span class="built_in">this</span>.primarySources = <span class="keyword">new</span> <span class="title class_">LinkedHashSet</span>&lt;&gt;(Arrays.asList(primarySources));</span><br><span class="line"><span class="comment">// 推断应用类型，默认是Servlet</span></span><br><span class="line"><span class="built_in">this</span>.webApplicationType = deduceWebApplicationType();</span><br><span class="line"><span class="comment">// 读取‘META-INF/spring.factories’中的接口的实现的配置，来初始化ApplicationContextInitializer</span></span><br><span class="line"><span class="comment">// ApplicationContextInitializer可以在ApplicationContext初始化过程中、refresh之前注册一系列回调来进行一些操作，比如配置文件的操作</span></span><br><span class="line">setInitializers((Collection) getSpringFactoriesInstances(</span><br><span class="line">				ApplicationContextInitializer.class));</span><br><span class="line">setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));</span><br><span class="line"><span class="comment">// 通过堆栈信息推断main函数所在类</span></span><br><span class="line"><span class="built_in">this</span>.mainApplicationClass = deduceMainApplicationClass();</span><br></pre></td></tr></table></figure>

<h2 id="run-启动流程"><a href="#run-启动流程" class="headerlink" title="run()启动流程"></a>run()启动流程</h2><p>SpringApplication初始化完成后，调用SpringApplication类的run()方法进入启动流程</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> ConfigurableApplicationContext <span class="title function_">run</span><span class="params">(String... args)</span> &#123;</span><br><span class="line">    <span class="comment">// 启动StopWatch，用于计时</span></span><br><span class="line">    <span class="comment">// “allowing for timing of a number of tasks, exposing total running time and running time for each named task.”</span></span><br><span class="line">    <span class="comment">// 启动完成时打印的“Started *** in *** seconds”就是StopWatch负责计时的</span></span><br><span class="line">	<span class="type">StopWatch</span> <span class="variable">stopWatch</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">StopWatch</span>();</span><br><span class="line">	stopWatch.start();</span><br><span class="line">	<span class="type">ConfigurableApplicationContext</span> <span class="variable">context</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">	<span class="comment">// 报告启动过程中异常的回调，可自定义</span></span><br><span class="line">	Collection&lt;SpringBootExceptionReporter&gt; exceptionReporters = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;();</span><br><span class="line">	<span class="comment">// 设置java.awt.headless属性</span></span><br><span class="line">	<span class="comment">// headless模式用于缺少显示屏、鼠标、键盘等情况下时，仍然可以使用graphic、canvas等</span></span><br><span class="line">	configureHeadlessProperty();</span><br><span class="line">	<span class="comment">// 通过读取‘META-INF/spring.factories’来初始化SpringApplicationRunListener</span></span><br><span class="line">	<span class="comment">// 默认只有一个EventPublishingRunListener，负责发布SpringApplicationEvent，实现了environmentPrepared、contextPrepared、contextLoaded、starting、started等的回调</span></span><br><span class="line">	<span class="type">SpringApplicationRunListeners</span> <span class="variable">listeners</span> <span class="operator">=</span> getRunListeners(args);</span><br><span class="line">	listeners.starting();</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">	    <span class="comment">// 读取参数</span></span><br><span class="line">		<span class="type">ApplicationArguments</span> <span class="variable">applicationArguments</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultApplicationArguments</span>(</span><br><span class="line">				args);</span><br><span class="line">		<span class="comment">// prepareEnvironment，创建和配置environment</span></span><br><span class="line">		<span class="type">ConfigurableEnvironment</span> <span class="variable">environment</span> <span class="operator">=</span> </span><br><span class="line">		    prepareEnvironment(listeners,</span><br><span class="line">				applicationArguments);</span><br><span class="line">		<span class="comment">// 设置spring.beaninfo.ignore，默认是true</span></span><br><span class="line">		configureIgnoreBeanInfo(environment);</span><br><span class="line">		<span class="comment">// 打印banner</span></span><br><span class="line">		<span class="type">Banner</span> <span class="variable">printedBanner</span> <span class="operator">=</span> printBanner(environment);</span><br><span class="line">		<span class="comment">// 创建ApplicationContext</span></span><br><span class="line">		<span class="comment">// createApplicationContext()方法是protected的，可以自定义，也可以使用setApplicationContextClass(Class)设置</span></span><br><span class="line">		<span class="comment">// 会先尝试使用自定义的“set application context or application contextclass”，没有使用setApplicationContextClass(Class)设置时，这一方法会通过反射创建一个默认的ApplicationContext</span></span><br><span class="line">		context = createApplicationContext();</span><br><span class="line">		<span class="comment">// 通过SpringFactories初始化exceptionReporters</span></span><br><span class="line">		exceptionReporters = getSpringFactoriesInstances(</span><br><span class="line">				SpringBootExceptionReporter.class,</span><br><span class="line">				<span class="keyword">new</span> <span class="title class_">Class</span>[] &#123; ConfigurableApplicationContext.class &#125;, context);</span><br><span class="line">		<span class="comment">// 配置ApplicationContext</span></span><br><span class="line">		prepareContext(context, environment, listeners, applicationArguments,</span><br><span class="line">				printedBanner);</span><br><span class="line">		<span class="comment">// 刷新ApplicationContext，初始化tomcat、加载bean、启动tomcat</span></span><br><span class="line">		refreshContext(context);</span><br><span class="line">		<span class="comment">// protected方法，可以自定义子类来作为刷新完成的回调</span></span><br><span class="line">		afterRefresh(context, applicationArguments);</span><br><span class="line">		<span class="comment">// 计时结束</span></span><br><span class="line">		stopWatch.stop();</span><br><span class="line">		<span class="comment">// 输出启动过程的计时信息等（Started MonitorcenterApplication in *** seconds (JVM running for ***)）</span></span><br><span class="line">		<span class="keyword">if</span> (<span class="built_in">this</span>.logStartupInfo) &#123;</span><br><span class="line">			<span class="keyword">new</span> <span class="title class_">StartupInfoLogger</span>(<span class="built_in">this</span>.mainApplicationClass)</span><br><span class="line">						.logStarted(getApplicationLog(), stopWatch);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// 通知listener started</span></span><br><span class="line">		listeners.started(context);</span><br><span class="line">		<span class="comment">// 调用各个runner，如ApplicationRunner、CommandLineRunner</span></span><br><span class="line">		callRunners(context, applicationArguments);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">		handleRunFailure(context, ex, exceptionReporters, listeners);</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">IllegalStateException</span>(ex);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		listeners.running(context);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">		handleRunFailure(context, ex, exceptionReporters, <span class="literal">null</span>);</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">IllegalStateException</span>(ex);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> context;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="prepareEnvironment——创建和配置environment"><a href="#prepareEnvironment——创建和配置environment" class="headerlink" title="prepareEnvironment——创建和配置environment"></a>prepareEnvironment——创建和配置environment</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> ConfigurableEnvironment <span class="title function_">prepareEnvironment</span><span class="params">(</span></span><br><span class="line"><span class="params">			SpringApplicationRunListeners listeners,</span></span><br><span class="line"><span class="params">			ApplicationArguments applicationArguments)</span> &#123;</span><br><span class="line">	<span class="comment">// Create and configure the environment</span></span><br><span class="line">	<span class="type">ConfigurableEnvironment</span> <span class="variable">environment</span> <span class="operator">=</span> getOrCreateEnvironment();</span><br><span class="line">	<span class="comment">// 配置environment的Property和Profile</span></span><br><span class="line">	<span class="comment">// 相关的函数configureEnvironment中调用的configurePropertySources、configureProfiles都是protected的，可以Override them for complete control over Environment customization</span></span><br><span class="line">	<span class="comment">// 此处处理了servertContext、system、cmd等property，还未加载application.properties之类文件的proterty</span></span><br><span class="line">	<span class="comment">// SpringApplication默认实现中，在configurePropertySources()方法中尝试添加defaultProperties(addLast)和commandLineArgs(addFirst，所以命令行指定的properties优先级高)，在configureProfiles()方法尝试确定active的profile（比如命令行指定了spring.profiles.active时）</span></span><br><span class="line">	configureEnvironment(environment, applicationArguments.getSourceArgs());</span><br><span class="line">	<span class="comment">// 监听器通知environmentPrepared</span></span><br><span class="line">	<span class="comment">// 其中，ConfigFileApplicationListener的回调中，通过‘META-INF/spring.factories’加载所有EnvironmentPostProcessor，并且自身也实现了EnvironmentPostProcessor并加入，然后调用所有EnvironmentPostProcessor；ConfigFileApplicationListener的实现中添加了random properties，然后load了application.properties等配置文件</span></span><br><span class="line">	<span class="comment">// 还有配置日志的LoggingApplicationListener等listenter</span></span><br><span class="line">	listeners.environmentPrepared(environment);</span><br><span class="line">	<span class="comment">// 绑定SpringApplication的environment即运行环境</span></span><br><span class="line">	bindToSpringApplication(environment);</span><br><span class="line">	<span class="keyword">if</span> (<span class="built_in">this</span>.webApplicationType == WebApplicationType.NONE) &#123;</span><br><span class="line">		environment = <span class="keyword">new</span> <span class="title class_">EnvironmentConverter</span>(getClassLoader())</span><br><span class="line">				.convertToStandardEnvironmentIfNecessary(environment);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 在environment上添加configurationProperties，放在第一个位置（首先被读取的），内容是已经添加的propertySources（查询配置时是在列表中从前往后找的）</span></span><br><span class="line">	ConfigurationPropertySources.attach(environment);</span><br><span class="line">	<span class="keyword">return</span> environment;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="ConfigFileApplicationListener加载配置"><a href="#ConfigFileApplicationListener加载配置" class="headerlink" title="ConfigFileApplicationListener加载配置"></a>ConfigFileApplicationListener加载配置</h4><p>ConfigFileApplicationListener首先加载了random配置，然后开始加载配置文件：</p>
<ul>
<li>读取通过环境变量等配置的active的profile；首先查找environment之前的配置（命令行、环境变量等）有无设置“spring.profiles.active”或”spring.profiles.include”，已经设置时将指定的profile下的property读入；将其他形式设置的active的profile下的property也读入；如果此时未读到active的profile，读取默认的配置文件，默认的配置文件可以使用”spring.profiles.default”设置，默认是“default”</li>
<li>从file:.&#x2F;config&#x2F;、file:.&#x2F;、classpath:&#x2F;config&#x2F;、classpath:&#x2F;application.properties四个默认路径（也可以自定义searchLocation）查找properties、xml、yml、yaml类型的配置文件，四个路径也按这一顺序形成优先级；加载active的配置文件和默认的配置文件（整个过程的代码比较多、比较绕，可见<a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_30635053/article/details/101944096%EF%BC%89">https://blog.csdn.net/weixin_30635053/article/details/101944096）</a></li>
</ul>
<p>最终，配置文件在list的顺序是：active的profile -&gt; 默认的profile</p>
<p>ConfigFileApplicationListener还在onApplicationPreparedEvent事件时添加了PropertySourceOrderingPostProcessor，将defaultProperties移动到list最后</p>
<h3 id="prepareContext——配置ApplicationContext"><a href="#prepareContext——配置ApplicationContext" class="headerlink" title="prepareContext——配置ApplicationContext"></a>prepareContext——配置ApplicationContext</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title function_">prepareContext</span><span class="params">(ConfigurableApplicationContext context,</span></span><br><span class="line"><span class="params">		ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,</span></span><br><span class="line"><span class="params">		ApplicationArguments applicationArguments, Banner printedBanner)</span>&#123;</span><br><span class="line">	<span class="comment">// 设置使用的environment</span></span><br><span class="line">	context.setEnvironment(environment);</span><br><span class="line">	<span class="comment">// 一些配置，默认的有beanNameGenerator、resourceLoader</span></span><br><span class="line">	<span class="comment">// 是protected方法，可以添加自定义配置</span></span><br><span class="line">	postProcessApplicationContext(context);</span><br><span class="line">	<span class="comment">// 调用各个ApplicationContextInitializer（在初始化SpringApplication时通过spring.factories加载）</span></span><br><span class="line">	<span class="comment">// 比如ServerPortInfoApplicationContextInitializer负责“sets Environment properties for the ports that &#123;@link WebServer&#125; servers are actually listening on”</span></span><br><span class="line">	applyInitializers(context);</span><br><span class="line">	<span class="comment">// 通知各个监听器contextPrepared，回调</span></span><br><span class="line">	listeners.contextPrepared(context);</span><br><span class="line">	<span class="keyword">if</span> (<span class="built_in">this</span>.logStartupInfo) &#123;</span><br><span class="line">		logStartupInfo(context.getParent() == <span class="literal">null</span>);</span><br><span class="line">		logStartupProfileInfo(context);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 添加applicationArguments作为一个bean</span></span><br><span class="line">	<span class="comment">// Add boot specific singleton beans</span></span><br><span class="line">	context.getBeanFactory().registerSingleton(<span class="string">&quot;springApplicationArguments&quot;</span>,</span><br><span class="line">			applicationArguments);</span><br><span class="line">	<span class="keyword">if</span> (printedBanner != <span class="literal">null</span>) &#123;</span><br><span class="line">		context.getBeanFactory().registerSingleton(<span class="string">&quot;springBootBanner&quot;</span>,printedBanner);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Load the sources</span></span><br><span class="line">	Set&lt;Object&gt; sources = getAllSources();</span><br><span class="line">	Assert.notEmpty(sources, <span class="string">&quot;Sources must not be empty&quot;</span>);</span><br><span class="line">	<span class="comment">// 向ApplicationContext加载必要的几个BeanDefinition</span></span><br><span class="line">	load(context, sources.toArray(<span class="keyword">new</span> <span class="title class_">Object</span>[<span class="number">0</span>]));</span><br><span class="line">	<span class="comment">// 通知listener contextLoaded</span></span><br><span class="line">	<span class="comment">// 注册了ApplicationContextAware接口的listener会回调setApplicationContext</span></span><br><span class="line">	<span class="comment">// 广播ApplicationPreparedEvent</span></span><br><span class="line">	listeners.contextLoaded(context);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="load——向ApplicationContext加载BeanDefinition"><a href="#load——向ApplicationContext加载BeanDefinition" class="headerlink" title="load——向ApplicationContext加载BeanDefinition"></a>load——向ApplicationContext加载BeanDefinition</h4><p>load中通过扫描注解从之前的primarySource加载BeanDefinition(也可以设置source)</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 查找注解</span></span><br><span class="line"><span class="keyword">if</span> (isComponent(source)) &#123;</span><br><span class="line">	<span class="built_in">this</span>.annotatedReader.register(source);</span><br><span class="line">	<span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其中，扫描注解使用的是AnnotationUtils类</p>
<h3 id="refreshContext——刷新ApplicationContext，加载bean"><a href="#refreshContext——刷新ApplicationContext，加载bean" class="headerlink" title="refreshContext——刷新ApplicationContext，加载bean"></a>refreshContext——刷新ApplicationContext，加载bean</h3><p>最终调用了AbstractApplicationContext类的refresh()方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 使用startupShutdownMonitor加锁</span></span><br><span class="line"><span class="comment">// 对startup和close过程中的refresh和destory bean的过程加锁</span></span><br><span class="line"><span class="keyword">synchronized</span> (<span class="built_in">this</span>.startupShutdownMonitor) &#123;</span><br><span class="line">	<span class="comment">// prepareRefresh</span></span><br><span class="line">	<span class="comment">// 留下了一个protected的initPropertySources()方法，可以实现子类来Replace any stub property sources with actual instances.</span></span><br><span class="line">	<span class="comment">// 然后验证标记为required的property</span></span><br><span class="line">	<span class="comment">// Prepare this context for refreshing.</span></span><br><span class="line">	prepareRefresh();</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 初始化bean factory</span></span><br><span class="line">	<span class="comment">// Tell the subclass to refresh the internal bean factory.</span></span><br><span class="line">	<span class="type">ConfigurableListableBeanFactory</span> <span class="variable">beanFactory</span> <span class="operator">=</span> obtainFreshBeanFactory();</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 设置ClassLoader、ignoreDependency等</span></span><br><span class="line">	<span class="comment">// 注册early post-processor for detecting inner beans as ApplicationListeners</span></span><br><span class="line">	<span class="comment">// 注册environment、systemProperties、systemEnvironment bean</span></span><br><span class="line">	<span class="comment">// Prepare the bean factory for use in this context.</span></span><br><span class="line">	prepareBeanFactory(beanFactory);</span><br><span class="line"></span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		<span class="comment">// protected方法，可以实现动态的添加、修改bean等操作</span></span><br><span class="line">		<span class="comment">// “Modify the application context&#x27;s internal bean factory after its standard initialization.”</span></span><br><span class="line">		<span class="comment">// Allows post-processing of the bean factory in context subclasses.</span></span><br><span class="line">		postProcessBeanFactory(beanFactory);</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 调用各个BeanFactoryPostProcessor</span></span><br><span class="line">		<span class="comment">// 调用BeanDefinitionRegistryPostProcessor来加载所有的BeanDefination，比如使用ConfigurationClassPostProcessor来加载所有@Configuration的类</span></span><br><span class="line">		<span class="comment">// 比如，ConfigFileApplicationListener在onApplicationPreparedEvent事件时添加了PropertySourceOrderingPostProcessor，如果defaultProperties存在，此时将其移动到list的最后</span></span><br><span class="line">		<span class="comment">// BeanFactoryPostProcessor是在加载了BeanDefination之后、bean实例化之前调用的</span></span><br><span class="line">		<span class="comment">// Invoke factory processors registered as beans in the context.</span></span><br><span class="line">		invokeBeanFactoryPostProcessors(beanFactory);</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 调用所有BeanPostProcessor</span></span><br><span class="line">		<span class="comment">// 在bean实例化之后执行，提供了两个回调</span></span><br><span class="line">		<span class="comment">// postProcessBeforeInitialization()，在bean实例化之后、初始化之前调用</span></span><br><span class="line">		<span class="comment">// postProcessAfterInitialization()，在bean实例化之后、初始化之后调用</span></span><br><span class="line">		<span class="comment">// Register bean processors that intercept bean creation.</span></span><br><span class="line">		registerBeanPostProcessors(beanFactory);</span><br><span class="line"></span><br><span class="line">		<span class="comment">// MessageSource，用于国际化等</span></span><br><span class="line">		<span class="comment">// Initialize message source for this context.</span></span><br><span class="line">		initMessageSource();</span><br><span class="line"></span><br><span class="line">		<span class="comment">// Initialize event multicaster for this context.</span></span><br><span class="line">		initApplicationEventMulticaster();</span><br><span class="line"></span><br><span class="line">		<span class="comment">// onRefresh()，protected方法，可以在子类中实现initialize other special beans</span></span><br><span class="line">		<span class="comment">// 对于servlet应用，实现的子类中调用了createWebServer()来读取配置、创建Tomcat web server</span></span><br><span class="line">		<span class="comment">// Initialize other special beans in specific context subclasses.</span></span><br><span class="line">		onRefresh();</span><br><span class="line"></span><br><span class="line">		<span class="comment">// Check for listener beans and register them.</span></span><br><span class="line">		registerListeners();</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 初始化bean</span></span><br><span class="line">		<span class="comment">// 最终调用了beanFactory.preInstantiateSingletons()</span></span><br><span class="line">		<span class="comment">// 调用bean的初始化方法initialization，以及所有实现了SmartInitializingSingleton接口的初始化后的回调post-initialization callback</span></span><br><span class="line">		<span class="comment">// 实现了Aware接口的bean在这一阶段实例化之后执行set***Aware()回调</span></span><br><span class="line">		<span class="comment">// Instantiate all remaining (non-lazy-init) singletons.</span></span><br><span class="line">		finishBeanFactoryInitialization(beanFactory);</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 初始化及调用lifecycleProcessor</span></span><br><span class="line">		<span class="comment">// 发布ContextRefreshedEvent事件</span></span><br><span class="line">		<span class="comment">// 对于servlet应用，开始startWebServer()，并发布ServletWebServerInitializedEvent事件</span></span><br><span class="line">		<span class="comment">// Last step: publish corresponding event.</span></span><br><span class="line">		finishRefresh();</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 以下代码省略</span></span><br><span class="line">	...</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="关于BeanFactoryPostProcessor和BeanPostProcessor"><a href="#关于BeanFactoryPostProcessor和BeanPostProcessor" class="headerlink" title="关于BeanFactoryPostProcessor和BeanPostProcessor"></a>关于BeanFactoryPostProcessor和BeanPostProcessor</h3><ul>
<li>BeanFactoryPostProcessor在加载了BeanDefination之后、实例化之前调用，可以用于修改未实例化的bean的各种属性</li>
<li>BeanPostProcessor在实例化之后调用，提供了初始化之前和初始化之后两个回调：postProcessBeforeInitialization()、postProcessAfterInitialization()</li>
<li>实例化对应的方法是：如果bean实现了InitializingBean接口，对应的方法为afterPropertiesSet；定义bean时init-method指定的方法</li>
</ul>
<p>要注意，在这里：</p>
<ul>
<li>实例化是Instantiation，是实例化一个bean</li>
<li>初始化是Initialization，是封装bean</li>
</ul>
<p>先Instantiation在Initialization，在调用postProcessBeforeInitialization()时，bean中各项@Autowired的依赖已经注入了</p>
<p>对于实现了Aware接口的bean，如EnvironmentAware、ResourceLoaderAware、ApplicationContextAware等，在实例化之后、初始化之前的会通过BeanPostProcessor的postProcessBeforeInitialization()执行set***Aware()回调方法</p>
<p>整个过程中，listener触发的回调有：starting-&gt;environmentPrepared-&gt;contextPrepared-&gt;contextLoaded-&gt;started-&gt;running</p>
<p>发送的ApplicationEvent主要有：ApplicationStartingEvent-&gt;ApplicationEnvironmentPreparedEvent-&gt;ApplicationPreparedEvent-&gt;ContextRefreshedEvent-&gt;ServletWebServerInitializedEvent-&gt;ApplicationStartedEvent-&gt;org.springframework.boot.context.event.ApplicationReadyEvent</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/java/" rel="tag"># java</a>
              <a href="/tags/Spring-Boot/" rel="tag"># Spring Boot</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/9b1b03df.html" rel="prev" title="使用ntp或chrony部署时间同步服务">
      <i class="fa fa-chevron-left"></i> 使用ntp或chrony部署时间同步服务
    </a></div>
      <div class="post-nav-item">
    <a href="/31d2f121.html" rel="next" title="ConcurrentHashMap源码学习（java 7）">
      ConcurrentHashMap源码学习（java 7） <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#SpringApplication%E7%9A%84%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="nav-number">1.</span> <span class="nav-text">SpringApplication的初始化</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#run-%E5%90%AF%E5%8A%A8%E6%B5%81%E7%A8%8B"><span class="nav-number">2.</span> <span class="nav-text">run()启动流程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#prepareEnvironment%E2%80%94%E2%80%94%E5%88%9B%E5%BB%BA%E5%92%8C%E9%85%8D%E7%BD%AEenvironment"><span class="nav-number">2.1.</span> <span class="nav-text">prepareEnvironment——创建和配置environment</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#ConfigFileApplicationListener%E5%8A%A0%E8%BD%BD%E9%85%8D%E7%BD%AE"><span class="nav-number">2.1.1.</span> <span class="nav-text">ConfigFileApplicationListener加载配置</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#prepareContext%E2%80%94%E2%80%94%E9%85%8D%E7%BD%AEApplicationContext"><span class="nav-number">2.2.</span> <span class="nav-text">prepareContext——配置ApplicationContext</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#load%E2%80%94%E2%80%94%E5%90%91ApplicationContext%E5%8A%A0%E8%BD%BDBeanDefinition"><span class="nav-number">2.2.1.</span> <span class="nav-text">load——向ApplicationContext加载BeanDefinition</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#refreshContext%E2%80%94%E2%80%94%E5%88%B7%E6%96%B0ApplicationContext%EF%BC%8C%E5%8A%A0%E8%BD%BDbean"><span class="nav-number">2.3.</span> <span class="nav-text">refreshContext——刷新ApplicationContext，加载bean</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%85%B3%E4%BA%8EBeanFactoryPostProcessor%E5%92%8CBeanPostProcessor"><span class="nav-number">2.4.</span> <span class="nav-text">关于BeanFactoryPostProcessor和BeanPostProcessor</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">马天</p>
  <div class="site-description" itemprop="description">程序猿</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">41</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">17</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">25</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/matian2014" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;matian2014" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:matian1103@qq.com" title="E-Mail → mailto:matian1103@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><a href="https://beian.miit.gov.cn/" rel="noopener" target="_blank">陕ICP备2023001563号 </a>
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">马天</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
